package com.huiminpay.transaction.service;

import com.alibaba.fastjson.JSON;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.IdWorkerUtils;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.merchant.api.IStoreService;
import com.huiminpay.merchant.dto.StoreDTO;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.AlipayBean;
import com.huiminpay.paymentagent.api.service.IAlipayAgentService;
import com.huiminpay.transaction.api.IPayChannelParamService;
import com.huiminpay.transaction.api.ITransactionService;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.dto.*;
import com.huiminpay.transaction.entity.PayOrder;
import com.huiminpay.transaction.mapper.PayOrderMapper;
import com.huiminpay.transaction.mq.MqConst;
import com.huiminpay.transaction.mq.PayProducer;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDateTime;


@Service
public class ITransactionServiceImpl implements ITransactionService {


    @Value("${qr.url}")
    String QrURL;

    @Reference
    IStoreService storeService;

    @Autowired
    PayOrderMapper payOrderMapper;

    @Reference
    IAlipayAgentService iAlipayAgentService;

    @Reference
    IPayChannelParamService  iPayChannelParamService;

    @Autowired
    PayProducer payProducer;

    @Override
    public String createQrURL(QRCodeDto qrCodeDto) {

        //因为缺少门店信息 先查询
        StoreDTO storeDto = storeService.queryById(qrCodeDto.getStoreId());
        qrCodeDto.setSubject(storeDto.getStoreName());
        qrCodeDto.setBody("备注信息");

        //对象转换
        PayOrderDTO payOrderDTO = new PayOrderDTO();
        BeanUtils.copyProperties(qrCodeDto,payOrderDTO);

        //拼接url
        String key = EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(payOrderDTO));
        String url = QrURL + key;


        return url;
    }

    @Override
    public String createAliPayOrder(PayOrderDTO payOrderDTO) throws Exception {

        //0.获取订单号，生成
        String tradeNo = IdWorkerUtils.getInstance().createUUID();
        /**
         * 支付通道
         */
        String payChannel = "ALIPAY_WAP";
        String channel = "huimin_c2b";
        //查询商店信息，获取商户id
        StoreDTO storeDTO = storeService.queryById(payOrderDTO.getStoreId());

        //1.创建支付订单
        OrderResultDTO orderResultDTO = PayOrderConvert.INSTANCE.request2dto(payOrderDTO);
        PayOrder payOrder = PayOrderConvert.INSTANCE.dto2entity(orderResultDTO);
        //设置参数
        payOrder.setTradeNo(tradeNo);
        payOrder.setMerchantId(storeDTO.getMerchantId());
        payOrder.setOutTradeNo(tradeNo);
        payOrder.setPayChannel(payChannel);
        payOrder.setChannel(channel);
        payOrder.setCurrency("CNY");
        /**
         * 设置订单状态,0-订单生成,1-支付中(目前未使用),2-支付成功,3-业务处理完成
         */
        payOrder.setTradeState("0");
        payOrder.setCreateTime(LocalDateTime.now());
        payOrder.setUpdateTime(LocalDateTime.now());
        //暂定 TODO
        //orderResultDTO.setProductCode("QUICK_WAP_PAY");
        payOrderMapper.insert(payOrder);


        //2.调用支付宝接口

        //设置请求参数
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOutTradeNo(tradeNo);
        alipayBean.setSubject(payOrderDTO.getSubject());
        alipayBean.setBody(payOrderDTO.getBody());

        /**
         * 设置金额   分转元
         */
        String ta = AmountUtil.changeF2Y(String.valueOf(payOrderDTO.getTotalAmount()));
        alipayBean.setTotalAmount(ta);
        alipayBean.setProductCode("QUICK_WAP_PAY");

        //设置公共参数
        //1.查询平台支付的公共参数
        PayChannelParamDTO payChannelParamDTO =
                iPayChannelParamService.queryPayChannelParam(payOrderDTO.getAppId(), channel, payChannel);

        String param = payChannelParamDTO.getParam();

        if(StringUtils.isEmpty(param)){
            throw new BusinessException(CommonErrorCode.UNKOWN);
        }

        AliConfigParam aliConfigParam = JSON.parseObject(param, AliConfigParam.class);
        aliConfigParam.setCharest("UTF-8");

        String doAlipayWepApi = iAlipayAgentService.doAlipayWepApi(aliConfigParam, alipayBean);


        /**
         * 3.mq通知 延时消息
         */
        PayOrderMqDto payOrderMqDto = new PayOrderMqDto();
        payOrderMqDto.setOutTradeNo(tradeNo);
        payOrderMqDto.setPayChannel(payChannel);
        payProducer.sendMsByDelay(MqConst.PAY_ORDER_LISTENER,payOrderMqDto);


        return doAlipayWepApi;



    }
}
